<?php
include("../includes/DBFunctions.php");

function animalReportFunctor($sid) {
	$db = new DBFunctions;
	$db->connectDB();
	$query = "call getSpeciesInfo(".$sid.",@a);";
	$result = $db->query($query);
	if( !$result ) {
		die("alert('Failed stored procedure call (getSpeciesInfo)');");
	}
	if (mysqli_num_rows($result) != 1) {
		$db->closeDB();
		$toPrint = "<div><h3>n/a</h3></div>";;
	} else {
		while( $line = mysqli_fetch_array( $result, MYSQL_ASSOC ) ) {
			$cName = $line['CommonName'];
			$toPrint = "<div><h3>".$cName." <i>(".$line['ScientificName'].")</i></h3><ul><li>Heat Tolerance: ".$line['MinHeat']." - ".$line['MaxHeat']."&deg; F</li>";
			$toPrint .= "<li>Weight: ".$line['HungerIndex']." lbs</li>";
			$toPrint .= "<li>Travel Speed: ".$line['TravelSpeed']." mph</li>";
			$toPrint .= "</ul></div>";
		}
		$db->closeDB();
	}
	
	$db->connectDB();
	$query = "call getSpeciesInfo_CanEat(".$sid.",@a);";
	$result = $db->query($query);
	if( !$result ) {
		die("alert('Failed stored procedure call (getSpeciesInfo_CanEat)');");
	}
	$toPrint .= "<div><h3>".$cName." Can Eat...</h3><ul>";
	if (mysqli_num_rows($result) < 1) {
		$db->closeDB();
		$toPrint .= "<li>n/a</li></ul></div>";
	} else {
		while( $line = mysqli_fetch_array( $result, MYSQL_ASSOC ) ) {
			$toPrint .= "<li>".$line['CommonName']." <i>(".$line['ScientificName'].")</i></li>";
		}
		$toPrint .= "</ul></div>";
		$db->closeDB();
	}
	
	$db->connectDB();
	$query = "call getSpeciesInfo_CanBeEatenBy(".$sid.",@a);";
	$result = $db->query($query);
	if( !$result ) {
		die("alert('Failed stored procedure call (getSpeciesInfo_CanEat)');");
	}
	$toPrint .= "<div><h3>".$cName." Can Be Eaten By...</h3><ul>";
	if (mysqli_num_rows($result) < 1) {
		$db->closeDB();
		$toPrint .= "<li>n/a</li></ul></div>";
	} else {
		while( $line = mysqli_fetch_array( $result, MYSQL_ASSOC ) ) {
			$onclick = "setTitle(\\\"<h2>Animal Report</h2>\\\");var s=new Array(\\\"sid=".$line['Species_ID']."\\\");call(\\\"functors/animalReportFunctor.php\\\",s,1,0);";
			$toPrint .= "<li><a href='#' onclick='".$onclick."'>".$line['CommonName']."</a> <i>(".$line['ScientificName'].")</i></li>";
		}
		$toPrint .= "</ul></div>";
		$db->closeDB();
	}
	
	echo 'displayReport("'.$toPrint.'");';
}

if( !isset($_POST['sid']) || $_POST['sid'] == '' ) {
	die("alert('No species was selected. Please try again.');");
}
$sid = $_POST['sid'];
animalReportFunctor($sid);
?>